package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Constant;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import dao.CommentedDao;

import util.KeyGen;
import util.MyJson;
import util.ParameterCheck;

/**
 * Servlet implementation class GetCommented
 */
public class GetCommented extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetCommented() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter pw = response.getWriter();
		Cookie[] cookies = request.getCookies();
		int page=ParameterCheck.intDefault(request.getParameter("index"));
		int pagecount=ParameterCheck.intDefault(request.getParameter("pagecount"));
		String key = "";
		for (int i = 0; i < cookies.length; i++) {
			if ("user".equals(cookies[i].getName()))
				key = cookies[i].getValue();
		}
		if (!KeyGen.cookieValid(key)) {
			pw.write(MyJson.toJson("msg", "-1"));
		} else {
			
			String uid=KeyGen.getId(key);
			CommentedDao ctdao=new CommentedDao();
			if(page<1 && pagecount==0){
				pagecount=ctdao.getCommentedCount(uid)/Constant.PageSize;
			}
			String mycomments=JSONArray.fromObject(ctdao.GetMyCommented(uid, page)).toString();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("res", mycomments);
			jsonObject.put("pagecount", pagecount);
			pw.write(jsonObject.toString());
		}
		pw.flush();
		pw.close();
	}

}
